package com.example.petshopping.ui.orders.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.petshopping.R;
import com.example.petshopping.ui.orders.OrderDetailActivity;
import com.example.petshopping.ui.orders.model.Order;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.OrderViewHolder> {

    private Context context;
    private List<Order> orderList;
    private List<Order> filteredList;
    private OnOrderActionListener listener;
    
    // 当前显示的订单类型（0: 全部, 1: 待付款, 2: 待发货, 3: 待收货, 4: 退款/售后）
    private int currentTab = 0;

    public interface OnOrderActionListener {
        void onLeftButtonClick(Order order, int position);
        void onRightButtonClick(Order order, int position);
    }

    public OrderAdapter(Context context, List<Order> orderList, OnOrderActionListener listener) {
        this.context = context;
        this.orderList = orderList != null ? orderList : new ArrayList<>();
        this.filteredList = new ArrayList<>(this.orderList);
        this.listener = listener;
    }

    @NonNull
    @Override
    public OrderViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_order, parent, false);
        return new OrderViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull OrderViewHolder holder, int position) {
        Order order = filteredList.get(position);
        
        // 绑定店铺信息
        holder.tvStoreName.setText(order.getStoreName());
        holder.ivStoreAvatar.setImageResource(order.getStoreAvatarResId());
        
        // 设置订单状态
        holder.tvOrderStatus.setText(order.getStatusText());
        
        // 绑定商品信息
        holder.tvProductTitle.setText(order.getProductTitle());
        holder.ivProductImage.setImageResource(order.getProductImageResId());
        holder.tvProductPrice.setText(order.getPrice());
        holder.tvProductQuantity.setText("x" + order.getQuantity());
        
        // 设置订单总金额
        holder.tvOrderAmount.setText(order.getTotalAmount());
        
        // 根据订单状态设置底部按钮
        setupButtons(holder, order);
        
        // 设置按钮点击事件
        final int pos = position;
        holder.btnLeft.setOnClickListener(v -> {
            if (listener != null) {
                listener.onLeftButtonClick(order, pos);
            }
        });
        
        holder.btnRight.setOnClickListener(v -> {
            if (listener != null) {
                listener.onRightButtonClick(order, pos);
            }
        });
        
        // 设置整个订单项的点击事件
        holder.itemView.setOnClickListener(v -> {
            navigateToOrderDetail(order);
        });
    }
    
    private void navigateToOrderDetail(Order order) {
        try {
            Intent intent = new Intent(context, OrderDetailActivity.class);
            intent.putExtra("order_id", order.getId());
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setupButtons(OrderViewHolder holder, Order order) {
        switch (order.getStatus()) {
            case Order.STATUS_PENDING_PAYMENT:
                holder.btnLeft.setText("取消订单");
                holder.btnRight.setText("继续付款");
                break;
                
            case Order.STATUS_PENDING_SHIPMENT:
                holder.btnLeft.setText("联系卖家");
                holder.btnRight.setText("提醒发货");
                break;
                
            case Order.STATUS_PENDING_RECEIPT:
                holder.btnLeft.setText("查看物流");
                holder.btnRight.setText("确认收货");
                break;
                
            case Order.STATUS_COMPLETED:
                holder.btnLeft.setText("申请退款");
                holder.btnRight.setText("再次购买");
                break;
                
            case Order.STATUS_REFUND:
                holder.btnLeft.setText("查看详情");
                holder.btnRight.setText("联系客服");
                break;
        }
    }

    @Override
    public int getItemCount() {
        return filteredList.size();
    }
    
    public void updateData(List<Order> orders) {
        this.orderList.clear();
        if (orders != null) {
            this.orderList.addAll(orders);
        }
        filterOrders(currentTab);
    }
    
    public void filterOrders(int tabPosition) {
        currentTab = tabPosition;
        filteredList.clear();
        
        if (tabPosition == 0) {
            // 全部订单
            filteredList.addAll(orderList);
        } else {
            // 根据状态筛选
            int status;
            switch (tabPosition) {
                case 1:
                    status = Order.STATUS_PENDING_PAYMENT;
                    break;
                case 2:
                    status = Order.STATUS_PENDING_SHIPMENT;
                    break;
                case 3:
                    status = Order.STATUS_PENDING_RECEIPT;
                    break;
                case 4:
                    status = Order.STATUS_REFUND;
                    break;
                default:
                    status = -1;
                    break;
            }
            
            for (Order order : orderList) {
                if (order.getStatus() == status) {
                    filteredList.add(order);
                }
            }
        }
        
        notifyDataSetChanged();
    }

    static class OrderViewHolder extends RecyclerView.ViewHolder {
        CircleImageView ivStoreAvatar;
        TextView tvStoreName, tvOrderStatus;
        ImageView ivProductImage;
        TextView tvProductTitle, tvProductPrice, tvProductQuantity, tvOrderAmount;
        Button btnLeft, btnRight;

        OrderViewHolder(@NonNull View itemView) {
            super(itemView);
            
            // 店铺信息
            ivStoreAvatar = itemView.findViewById(R.id.iv_store_avatar);
            tvStoreName = itemView.findViewById(R.id.tv_store_name);
            tvOrderStatus = itemView.findViewById(R.id.tv_order_status);
            
            // 商品信息
            ivProductImage = itemView.findViewById(R.id.iv_product_image);
            tvProductTitle = itemView.findViewById(R.id.tv_product_title);
            tvProductPrice = itemView.findViewById(R.id.tv_product_price);
            tvProductQuantity = itemView.findViewById(R.id.tv_product_quantity);
            
            // 订单金额
            tvOrderAmount = itemView.findViewById(R.id.tv_order_amount);
            
            // 底部按钮
            btnLeft = itemView.findViewById(R.id.btn_left);
            btnRight = itemView.findViewById(R.id.btn_right);
        }
    }
} 